package org.example.controller;

import org.example.config.PropertiesConfig;
import org.example.param.ArticleAddParam;
import org.example.param.ArticleAuthorParam;
import org.example.param.ArticleFuzzyParam;
import org.example.param.ArticleUpdateParam;
import org.example.service.ArticleService;
import org.example.utils.FileUploadUtil;
import org.example.utils.Result;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private ArticleService articleService;

    @GetMapping("/all")
    public Result all(){
        return articleService.all();
    }

    @PostMapping("add")
    @PreAuthorize("hasAnyRole('admin','normal')")
    public Result add(@RequestBody @Validated ArticleAddParam articleAddParam){
        return articleService.add(articleAddParam);
    }

    @PostMapping("delete")
    @PreAuthorize("hasAnyRole('admin','normal')")
    public Result delete(@RequestBody Map<String,Long> map){
        Long id = map.get("id");
        return articleService.delete(id);
    }

    @PostMapping("update")
    @PreAuthorize("hasAnyRole('admin','normal')")
    public Result update(@RequestBody @Validated ArticleUpdateParam articleUpdateParam){
        return articleService.update(articleUpdateParam);
    }

    // select

    /**
     * 模糊查找文章
     */
    @PostMapping("fuzzy")
    @PreAuthorize("permitAll()")
    public Result fuzzy(@RequestBody ArticleFuzzyParam articleFuzzyParam){
        return articleService.fuzzy(articleFuzzyParam);
    }


    /**
     * 根据id查找文章
     * @param map
     * @return
     */
    @PostMapping("findArticleById")
    @PreAuthorize("permitAll()")
    public Result findArticleById(@RequestBody Map<String,Long> map){
        Long id = map.get("id");
        return articleService.findArticleById(id);
    }

    /**
     * 根据作者来查找文章
     */
    @PostMapping("findArticleByAuthor")
    @PreAuthorize("permitAll()")
    public Result findArticleByAuthor(@RequestBody @Validated ArticleAuthorParam articleAuthorParam){
        return articleService.findArticleByAuthor(articleAuthorParam);
    }

    /**
     * 文章的文件上传
     */
    @PostMapping("uploadFile")
    @PreAuthorize("hasAnyRole('admin','normal')")
    public Result uploadFile(@RequestParam("image") MultipartFile file) throws IOException {
        String url = FileUploadUtil.upload(PropertiesConfig.getUploadFileDir(), file, FileUploadUtil.DEFAULT_ALLOWED_EXTENSION);
        return Result.success(FileUploadUtil.transformUrl(url));
    }
}
